package com.kly.interview.blackip;

import com.alibaba.nacos.api.annotation.NacosInjected;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author admin
 * @date 2025/5/4
 */
@Component
@Slf4j
public class NacosListener implements InitializingBean {

    @Value("${nacos.config.data-id}")
    private String dataId;

    @Value("${nacos.config.group}")
    private String group;

    @NacosInjected
    private ConfigService configService;

    @Override
    public void afterPropertiesSet() throws Exception {
        log.info("NacosListener init");
        String config = configService.getConfigAndSignListener(dataId, group, 5000, new Listener() {

            final ThreadFactory threadFactory = new ThreadFactory() {
                private final AtomicInteger atomicInteger = new AtomicInteger(1);

                @Override
                public Thread newThread(@NotNull Runnable r) {
                    Thread thread = new Thread(r);
                    thread.setName("NacosListener-" + atomicInteger.getAndIncrement());
                    return thread;
                }
            };

            final ExecutorService pool = Executors.newFixedThreadPool(1, threadFactory);

            @Override
            public Executor getExecutor() {
                return pool;
            }

            @Override
            public void receiveConfigInfo(String s) {
                log.info("config changed");
                BlackIpUtil.rebuildBlackIp(s);
            }
        });

        BlackIpUtil.rebuildBlackIp(config);
    }
}
